package com.changyou.skynet.task.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.changyou.skynet.task.dao.TaskDao;
import com.changyou.skynet.task.domain.TSTimeTaskEntity;
import com.changyou.skynet.task.domain.pageModel.TimeTask;
import com.changyou.skynet.task.service.DynamicTask;
import com.changyou.skynet.task.service.TaskService;
import com.changyou.skynet.web.domain.page.DataGrid;

@Service("taskService")
public class TaskServiceImpl implements TaskService {
    private static final Logger logger = LoggerFactory
            .getLogger(TaskServiceImpl.class);
    @Autowired
    private TaskDao taskDao;
    @Autowired
    private DynamicTask dynamicTask;
    private boolean initFinishFlag = false;
    /**
     * 添加一个任务
     */
    public boolean addTask(TimeTask task) {
        TSTimeTaskEntity target = new TSTimeTaskEntity();
        BeanUtils.copyProperties(task, target);
        target.setIsStart("0");
        if (true == dynamicTask.addTrigger(target)) {
            if (null != taskDao.save(target)) {
                return true;
            }else {
                logger.info("addTask taskDao save error.");
            }
        } else {
            logger.info("addTask dynamicTask addTrigger error.");
        }
        return false;
    }
    /**
     * 修改一个任务
     */
    public boolean editTask(TimeTask task) {
        logger.info("edit task {}" + task.toString());
        TSTimeTaskEntity t = taskDao.find(task.getId());
        if (null != t) {
            // 只有未启动的任务可以修改
            if (t.getIsStart().equals("0")) {
                task.setIsStart("0");
                BeanUtils.copyProperties(task, t);
                return true;
            }
        }
        return false;
    }
    /**
     * 页面显示任务
     */
    public DataGrid<TimeTask> datagrid(TimeTask task) {
        TSTimeTaskEntity target = new TSTimeTaskEntity();
        BeanUtils.copyProperties(task, target);
        DataGrid<TimeTask> dataGrid = new DataGrid<TimeTask>();
        String hql = " from TSTimeTaskEntity t ";
        Map<String, Object> params = new HashMap<String, Object>();
        long total = taskDao.count("select count(*) " + hql, params);
        if (total > 0) {
            List<TSTimeTaskEntity> list = taskDao.find(hql, params);
            List<TimeTask> retList = new ArrayList<TimeTask>();
            for (TSTimeTaskEntity e : list) {
                TimeTask t = new TimeTask();
                BeanUtils.copyProperties(e, t);
                retList.add(t);
            }
            dataGrid.setRows(retList);
        }
        dataGrid.setTotal(total);
        return dataGrid;
    }
    /**
     * 启动一个任务或者停止一个任务
     */
    public boolean startOrStopTask(String id, String start) {
        boolean isStart = start.equals("1");
        TSTimeTaskEntity task = taskDao.find(id);
        //初始化完成后。不允许重复提交相同的操作
        if (initFinishFlag && task.getIsStart().equals(start)) {
            logger.info("startOrStopTask start is not change");
            return true;
        }
        if (null != task) {
            if (true == dynamicTask.startOrStop(task.getTaskId(), isStart)) {
                task.setIsStart(start);
            }
            return true;
        }
        return false;
    }

    /**
     * 从数据库中初始化所有任务
     * 
     * @return
     */
    public boolean initTaskFromDB() {
        if (!initFinishFlag) {
            //添加支持的Job
            dynamicTask.addValidJob();
            Map<String, Object> params = new HashMap<String, Object>();
            String hql = " from TSTimeTaskEntity t "
                    + "where t.isEffect = :isEffect";
            params.put("isEffect", "1");
            List<TSTimeTaskEntity> tasks = taskDao.find(hql, params);
            for (TSTimeTaskEntity task : tasks) {
                // 创建任务
                dynamicTask.addTrigger(task);
                // 执行任务
                startOrStopTask(task.getId(), task.getIsStart());
            }
            initFinishFlag = true;
        }
        return true;
    }
    /**
     * 删除一个任务
     */
    public boolean delete(String id) {
        if (null == id || id.equals("")) {
            logger.error("delete error: id is empty.");
            return true;
        }
        TSTimeTaskEntity task = taskDao.find(id);
        // 任务运行中，不可以删除；
        if (task.getIsStart().equals("1")) {
            return false;
        }
        if (dynamicTask.deleteJobTrigger(task)) {
            taskDao.delete(id);
            return true;
        }
        return false;
    }
    /**
     * 支持任务调用的方法列表
     */
    public List<String> getTaskTypeList() {
        List<String> list = new ArrayList<String>();
        Set<String> taskSet = DynamicTask.getJobNameSet();
        for (String taskName : taskSet) {
            list.add(taskName);
        }
        return list;
    }

}
